#pragma once
#include "Sock.hpp"
#include <cstdlib>
#include<iostream>
#include<functional>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>

class HttpServer
{
public:
    using func_t = std::function<void(int)>;
    HttpServer(const uint16_t& port, func_t func)
    :_port(port),_func(func)
    {
        _serversock = _sock.Socket();
        _sock.Bind(_serversock, _port);
        _sock.Listen(_serversock);
    }
    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        while(true)
        {
            std::string client_ip;
            uint16_t client_port=0;
            int sockfd = _sock.Accept(_serversock, &client_port, &client_ip);
            if(sockfd < 0)
            {
                continue;
            }
            if(fork() == 0)
            {
                close(_serversock);
                _func(sockfd);
                close(sockfd);
                exit(-1);
            }
            close(sockfd);
        }
    }
    ~HttpServer(){
        if(_serversock >= 0){
            close(_serversock);
        }
    }
private:
    int _serversock;
    uint16_t _port;
    Sock _sock;
    func_t _func;
};
